package com.em.tuppence.web.services.client;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.ws.rs.core.MediaType;

import com.em.tuppence.core.model.application.User;
import com.em.tuppence.core.model.exceptions.TuppenceUserAlreadyExistsException;
import com.em.tuppence.services.IUserService;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;

public class UserServiceProxy implements IUserService {

	private Client client = null;
	
	public UserServiceProxy() {
		this.client = UserServiceClientFactory.INSTANCE.getClient();
	}

	@Override
	public User getUser(String userOpenIdUrl) {
		WebResource resource = null;
		User result = null;
		try {
			//look up resource
			resource = client.resource("http://localhost:2552/user/get/" + URLEncoder.encode(userOpenIdUrl,"utf8"));
			//get result		
			ClientResponse clientResponse = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
			
			//do status checking
			if(clientResponse.getStatus() == 200 || clientResponse.getStatus() == 201) {
				//get entity
				result = clientResponse.getEntity(User.class);
			} else {
				//bad response
				result = null;
			}
			
			//close
			clientResponse.close();
		} catch (UnsupportedEncodingException e) {
			//e.printStackTrace();
			result = null;
		} catch (UniformInterfaceException ufiex) {
			//ufiex.printStackTrace();
			result = null;
		}
		
		return result;
	}

	@Override
	public void addUser(User user) throws TuppenceUserAlreadyExistsException {
		//add user in backend
		try {
			//look up resource
			WebResource resource = client.resource("http://localhost:2552/user/add");
			ClientResponse clientResponse = resource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, user);
			
			if(clientResponse.getStatus() != 201) {
				//?
			}
			
			//get status
			//Boolean output = clientResponse.getEntity(Boolean.class);
			
			//close client response
			clientResponse.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}		
	}

	@Override
	public void updateUser(User user) {

		
	}

	@Override
	public void removeUser(User user) {

		
	}
	
	public void destroy() {
		//leaky abstraction
		if(this.client != null) {
			this.client.destroy();
		}
	}
	
}
